package com.atguigu.spzx.order.service.impl;

import com.atguigu.spzx.common.service.exception.GuiguException;
import com.atguigu.spzx.common.util.AuthContextUtil;
import com.atguigu.spzx.feign.cart.CartFeignClient;
import com.atguigu.spzx.feign.user.UserAddressFeignClient;
import com.atguigu.spzx.model.dto.h5.OrderInfoDto;
import com.atguigu.spzx.model.dto.h5.ProductSkuDto;
import com.atguigu.spzx.model.entity.h5.CartInfo;
import com.atguigu.spzx.model.entity.h5.UserAddress;
import com.atguigu.spzx.model.entity.order.OrderInfo;
import com.atguigu.spzx.model.entity.order.OrderItem;
import com.atguigu.spzx.model.entity.order.OrderLog;
import com.atguigu.spzx.model.entity.product.ProductSku;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.h5.TradeVo;
import com.atguigu.spzx.order.mapper.OrderInfoMapper;
import com.atguigu.spzx.order.mapper.OrderItemMapper;
import com.atguigu.spzx.order.mapper.OrderLogMapper;
import com.atguigu.spzx.order.service.OrderInfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: OrderInfoServiceImpl
 * @Package: com.atguigu.spzx.order.service.impl
 * @Description
 * @Author 孤妤
 * @Date: 2023/12/20 18:15
 */
@Service
@Transactional
public class OrderInfoServiceImpl implements OrderInfoService {
    @Autowired
    private CartFeignClient cartFeignClient; // 购物车远程调用
    @Autowired
    private UserAddressFeignClient userAddressFeignClient; // 用户远程调用
    @Autowired
    private OrderInfoMapper orderInfoMapper; // 订单数据
    @Autowired
    private OrderItemMapper orderItemMapper; // 订单明细
    @Autowired
    private OrderLogMapper orderLogMapper; // 订单日志
    @Override
    @Transactional(readOnly = true)
    public TradeVo findOrderInfo() {
        // 远程调用查询选中的商品
        List<CartInfo> cartInfoList = cartFeignClient.findCart();
        // 获取商品的总额
        BigDecimal bigDecimal = new BigDecimal("0.0");
        for (CartInfo cartInfo : cartInfoList) {
            BigDecimal multiply = new BigDecimal(cartInfo.getSkuNum());
            bigDecimal = bigDecimal.add(multiply.multiply(cartInfo.getCartPrice()));
        }
        // 创建响应的Trade对象并为总额赋值
        TradeVo tradeVo = new TradeVo();
        tradeVo.setTotalAmount(bigDecimal);
        // 创建orderItemList对象
        List<OrderItem> orderItemList = new ArrayList<>();
        // 将cartInfoList对象转为orderItemList对象
        cartInfoList.forEach(item -> {
            OrderItem orderItem = new OrderItem();
            orderItem.setSkuId(item.getSkuId());
            orderItem.setSkuName(item.getSkuName());
            orderItem.setSkuNum(item.getSkuNum());
            orderItem.setSkuPrice(item.getCartPrice());
            orderItem.setThumbImg(item.getImgUrl());
            orderItemList.add(orderItem);
        });
        tradeVo.setOrderItemList(orderItemList);
        return tradeVo;
    }

    @Override
    public Long submitOrder(OrderInfoDto orderInfoDto) {
        // 获取提交订单的购物车所有商品
        List<OrderItem> orderItemList = orderInfoDto.getOrderItemList();
        // 数据校验,查询购物车商品库存
        List<ProductSku> productSkuList = orderInfoMapper.selectProductSku(orderItemList);
        for (ProductSku itemSku : productSkuList) {
            for (OrderItem itemOrder : orderItemList) {
                // 商品的库存是否大于购物车商品的购买数量
                if (itemSku.getId().equals(itemOrder.getSkuId())) {
                    if (!(itemSku.getStockNum().compareTo(itemOrder.getSkuNum()) >= 0)) {
                        throw new GuiguException(209, itemOrder.getSkuName() + "的库存量不足,剩余" + itemSku.getStockNum());
                    }
                }
            }
        }
        // 远程调用获取用户最终选择的地址
        UserAddress userAddress = userAddressFeignClient.findUserAddressById(orderInfoDto.getUserAddressId());
        // 构建订单数据
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userAddress.getUserId());
        orderInfo.setNickName(userAddress.getPhone());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        // 构建订单号
        orderInfo.setOrderNo(String.valueOf(System.currentTimeMillis()));
        // 获取订单总额
        BigDecimal bigDecimal = new BigDecimal("0.0");
        for (OrderItem orderItem : orderItemList) {
            BigDecimal multiply = new BigDecimal(orderItem.getSkuNum());
            bigDecimal = bigDecimal.add(multiply.multiply(orderItem.getSkuPrice()));
        }
        orderInfo.setTotalAmount(bigDecimal);
        orderInfo.setOriginalTotalAmount(bigDecimal);
        orderInfo.setFeightFee(orderInfoDto.getFeightFee());
        orderInfo.setPayType(2);
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());
        orderInfo.setRemark(orderInfoDto.getRemark());
        // 保存订单
        orderInfoMapper.insertOrderInfo(orderInfo);
        // 获取orderId
        Long orderId = orderInfo.getId();
        // 保存订单明细
        orderItemList.forEach(item->{item.setOrderId(orderId);});
        orderItemMapper.insertOrderItem(orderItemList);
        // 记录日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderId);
        orderLog.setProcessStatus(0);
        orderLog.setNote("提交订单");
        orderLogMapper.insertOrderLog(orderLog);
        // 清空购物车数据
        cartFeignClient.deleteChecked();
        return orderId;
    }

    @Override
    @Transactional(readOnly = true)
    public OrderInfo findOrderInfoByOrderId(Long orderId) {
        return orderInfoMapper.selectOrderInfoByOrderId(orderId);
    }
    @Override
    @Transactional(readOnly = true)
    public TradeVo findOrderInfoBySkuId(Long skuId) {
        // 创建响应对象
        TradeVo tradeVo = new TradeVo();
        // 获取商品
        ProductSku productSku = orderInfoMapper.selectProductSkuBySkuId(skuId);
        // 创建orderItem
        OrderItem orderItem = new OrderItem();
        List<OrderItem> orderItemList = new ArrayList<>();
        BeanUtils.copyProperties(productSku,orderItem);
        orderItem.setSkuId(skuId);
        orderItem.setSkuPrice(productSku.getSalePrice());
        orderItem.setSkuNum(1);
        orderItemList.add(orderItem);
        tradeVo.setTotalAmount(productSku.getSalePrice());
        tradeVo.setOrderItemList(orderItemList);
        return tradeVo;
    }

    @Override
    public PageInfo<OrderInfo> findMyOrderPage(Integer page, Integer limit, Integer orderStatus) {
        // 进行分页
        PageHelper.startPage(page, limit);
        // 获取当前用户的userId
        Long userId = AuthContextUtil.getUserInfo().getId();
        // 根据用户id查询订单数据
        List<OrderInfo> orderInfoList = orderInfoMapper.findOrderInfoByUserIdPage(userId, orderStatus);
        return new PageInfo<>(orderInfoList,limit);
    }
}

